package com.zjjt.dc.modules.datacatch.service.blh.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zjjt.dc.modules.datacatch.entity.blh.DcCatchDataBlhProductInfo;
import com.zjjt.dc.modules.datacatch.service.blh.IBLHDataDealService;
import com.zjjt.dc.modules.datacatch.service.blh.IDcCatchDataBlhProductInfoService;
import com.zjjt.dc.tools.upload.file.action.AliOssBucketUploadFileAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @Description: 百礼汇数据处理服务
 */
@Slf4j
@Service
public class BLHDataDealService implements IBLHDataDealService {


    @Autowired
    private IDcCatchDataBlhProductInfoService dcCatchDataBlhProductInfoService;


    @Override
    public void updateGoodsImages(int startIdx, int limitNum, List<String> goodsIds) {
        try {
            if (ObjectUtil.isEmpty(goodsIds)) {
                goodsIds = new ArrayList<>();
                List<Long> dataIds = dcCatchDataBlhProductInfoService.getIds();
                for (Long dataId : dataIds) {
                    goodsIds.add(String.valueOf(dataId));
                }
            }

            updateGoodsImagesInfo(goodsIds.subList(startIdx, Math.min(startIdx + limitNum, goodsIds.size())));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新商品数据异常：{}", e.getMessage());
        }
    }

    /**
     * 下载存储图片
     *
     * @param ids
     */

    private void updateGoodsImagesInfo(List<String> ids) {
        ids.forEach(id -> {
            DcCatchDataBlhProductInfo info = dcCatchDataBlhProductInfoService.getById(id);
            if (ObjectUtils.isNotEmpty(info)) {
                Set<String> uniqueImages = new LinkedHashSet<>();
                uniqueImages.addAll(extractImageUrls(info.getProductImages()));
                uniqueImages.addAll(extractImageUrls(info.getImages()));
                uniqueImages.addAll(extractImageUrls(info.getProductInfos()));
                uniqueImages.addAll(extractImageUrls(info.getAppletIntroduce()));
                List<String> images = new ArrayList<>(uniqueImages);
                Map<String, String> newAddrMapper = null;
                try {
                    newAddrMapper = new AliOssBucketUploadFileAction("./download/blh/" + id, id, "yunpai").actionFiles(images);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                info.setProductImagesNew(replaceImageUrls(newAddrMapper, info.getProductImages()));
                info.setImagesNew(replaceImageUrls(newAddrMapper, info.getImages()));
                info.setProductInfosNew(replaceImageUrls(newAddrMapper, info.getProductInfos()));
                info.setAppletIntroduceNew(replaceImageUrls(newAddrMapper, info.getAppletIntroduce()));
                dcCatchDataBlhProductInfoService.updateById(info);


            }
        });
    }

    /**
     * 正则匹配图片链接
     */
    public List<String> extractImageUrls(String htmlContent) {
        Set<String> uniqueUrls = new LinkedHashSet<>(); // 保持插入顺序
        Pattern pattern = Pattern.compile(
                "https?://[\\w\\-\\.\\/~]+\\.(jpg|jpeg|png|gif|webp)(?:\\?[\\w\\-\\.=;&%]*)?",
                Pattern.CASE_INSENSITIVE
        );
        Matcher matcher = pattern.matcher(htmlContent); // 创建匹配器
        while (matcher.find()) {
            uniqueUrls.add(matcher.group());
        }

        return new ArrayList<>(uniqueUrls);
    }

    /**
     * 正则替换图片链接
     */
    public String replaceImageUrls(Map<String, String> newAddrMapper, String htmlContent) {
        Set<String> originUrls = newAddrMapper.keySet();
        String result = htmlContent;
        for (String originUrl : originUrls) {
            if (htmlContent.contains(originUrl)) {
                result = result.replace(originUrl, newAddrMapper.get(originUrl));
            }
        }
        return result;
    }

}
